<template>
	<view class="wrapper">
		<view class="login main-flex">
			<!--#ifdef MP-WEIXIN-->
			<view class="login-bar" :style="{height: `${setStore?.menuButton?.top || 0}px`}"></view>
			<!-- #endif -->
			<view class="login-app">
				<view class="login-logo">
					<image class="login-logo-img" :src="imgUrl(setStore.appLogo)"></image>
				</view>
				<view class="login-name">{{setStore.appName}}</view>
			</view>
			<view class="login-content">
				<!--#ifdef MP-WEIXIN-->
				<view class="login-content-title">为了为您提供更优质的服务，我们需要你的手机号码登录</view>
				<!-- #endif -->
				<!--#ifndef MP-WEIXIN-->
				<view class="login-content-tabs main-flex">
					<u-tabs
						:current="tabsCurrent"
						:list=" tabsList"
						lineColor="#e3230e"
						:lineWidth="lineWidth"
						lineHeight="8rpx"
						:itemStyle="{
							height: '64rpx',
							padding: '0 50rpx'
						}"
						:inactiveStyle="{
							color: '#333333',
							fontSize: '26rpx',
							fontWeight: 400
						}"
						:activeStyle="{
							color: '#e3230e',
							fontSize: '26rpx',
							transform: 'scale(1.077)',
							fontWeight: 400
						}"
						@change="changeTabs"></u-tabs>
				</view>
				<!-- #endif -->
				<view class="login-content-form" v-show="tabsCurrent === 0">
					<uni-forms
						:modelValue="formData1"
						ref="formRef1"
						:label-width="80"
						:rules="rules1">
						<uni-forms-item label="手机号码" name="phone">
							<uni-easyinput type="text" v-model="formData1.phone" placeholder="请输入手机号码" />
						</uni-forms-item>
						<uni-forms-item label="密码" name="password">
							<uni-easyinput type="password" v-model="formData1.password" placeholder="请输入密码" />
						</uni-forms-item>
					</uni-forms>
				</view>
				<view class="login-content-form" v-show="tabsCurrent === 1">
					<uni-forms
						:modelValue="formData"
						ref="formRef"
						:label-width="80"
						:rules="rules">
						<uni-forms-item label="手机号码" name="phone">
							<uni-easyinput type="text" v-model="formData.phone" placeholder="请输入手机号码" />
						</uni-forms-item>
						<uni-forms-item label="验证码" name="code">
							<view class="login-code main-flex">
								<view class="main-flex-item">
									<uni-easyinput type="text" v-model="formData.code" placeholder="请输入验证码" />
								</view>
								<button class="login-code-btn main-flex" @click="getCode">{{tips}}</button>
							</view>
						</uni-forms-item>
					</uni-forms>
					<u-code
						:seconds="seconds"
						@end="end"
						@start="start"
						ref="codeRef" 
						@change="codeChange"></u-code>
				</view>
				<!--#ifndef MP-WEIXIN-->
				<view class="login-forget" v-show="tabsCurrent === 0" @click="forget">
					忘记密码
				</view>
				<!--#endif-->
				<button :loading="isSubmit" :disabled="isSubmit" class="ty-button ty-button-confirm login-btn" @click="submitForm">登录</button>
				<!--#ifdef MP-WEIXIN-->
				<button class="ty-button ty-button-cancel login-btn" @click="cancel">取消</button>
				<!--#endif-->
				<!--#ifndef MP-WEIXIN-->
				<view class="login-tip" v-show="tabsCurrent === 0">
					还没有账号?
					<text class="login-tip-register" @click="register">马上注册</text>
				</view>
				<view class="login-tip" v-show="tabsCurrent === 1">
					已有账号和密码：
					<text class="login-tip-register" @click="goLogin">请使用密码登录</text>
				</view>
				<!--#endif-->
			</view>
			<view class="login-agreement main-flex" @click="changeAgreement">
				<uni-icons class="login-agreement-icon" :type="isAgreement?'checkbox-filled':'circle'" size="20" :color="isAgreement?'#e3230e':'#666666'"></uni-icons>
				<text>我已阅读并同意</text>
				<text class="login-agreement-item" @click.stop="goAgreement(1)">《服务协议》</text>
				<text>和</text>
				<text class="login-agreement-item" @click.stop="goAgreement(2)">《隐私政策》</text>
			</view>
		</view>
		
		<!--切换域名-->
		<u-popup :show="showUrl" :round="10" mode="center"  @close="closeUrl" @open="openUrl">
			<view class="url">
				<view class="url-title">更换服务器地址</view>
				<view class="url-input">
					<u-input
					placeholder="请输入服务器地址"
					border="surround"
					v-model="chooseUrl">
					</u-input>
				</view>
				<view class="url-radio">
					<u-radio-group
						v-model="chooseUrl"
						placement="column"
						@change="groupChangeUrl">
						<u-radio
							v-for="(item, index) in urlList"
							:key="index"
							:label="item"
							:name="item"
						>
						</u-radio>
					</u-radio-group>
				</view>
				<u-button type="primary" @click="submitUrl">确认</u-button>
			</view>
		</u-popup>
		
	</view>
</template>

<script setup>
import { computed, ref, watch } from 'vue';
import { onReady, onLoad, onReachBottom, onShow, onHide } from '@dcloudio/uni-app';
import useUserStore from '@/store/modules/user'
import useSetStore from '@/store/modules/set'
import { appletBindPhone, getNodeMsg, phoneCodeLogin, login } from "@/api/app_api/login"
import { setToken } from '@/utils/auth'
import modal from '@/plugins/modal'
import { throttle, debounce, test, sleep } from '@/uni_modules/uview-plus'
import md5 from 'js-md5'
import config from '@/config.js'
	const userStore = useUserStore()
	const setStore = useSetStore()
	const globalConfig = ref(config)
	
	const tabsList = ref([
		{ type: 1, name: '密码登录' },
		{ type: 2, name: '验证码登录' }
	])
	const lineWidth = ref('84rpx')
	// #ifdef MP-WEIXIN 
	const tabsCurrent = ref(1)
	// #endif
	// #ifndef MP-WEIXIN
	const tabsCurrent = ref(0)
	// #endif
	
	const changeTabs = (e) => {
		lineWidth.value = e.index === 0 ? '84rpx' : '110rpx'
		tabsCurrent.value = e.index
	}
	
	const formRef = ref(null)
	const formData = ref({
		phone: '',
		code: ''
	})
	// 表单验证
	const rules = ref({
		phone: {
			rules: [{
				required: true,
				errorMessage: '请输入手机号码'
			}, {
				validateFunction: function (rule,value,data,callback) {
					if (!test.mobile(value)) {
						callback('请输入正确手机号码')
					}
					return true
				}
			}]
		},
		code: {
			rules: [{
				required: true,
				errorMessage: '请输入验证码'
			}]
		}
	})
	
	// 验证码相关
	const tips = ref('获取验证码')
	const seconds = ref(60)
	const codeRef = ref(null)
	const codeChange = (text) => {
		tips.value = text
	}
	const end = () => {
		console.log('结束')
	}
	const start = () => {
		console.log('开始')
	}
	const getCode = () => {
		if (!formData.value.phone || !test.mobile(formData.value.phone)) return uni.$u.toast('请输入正确手机号码')
		if(codeRef.value.canGetCode) {
			getNodeMsg({
				phone: formData.value.phone,
				status: 0,
				code: md5(`zyzy&${formData.value.phone}`)
			}).then(res => {
				uni.$u.toast('验证码已发送')
				codeRef.value.start()
			})
		} else {
			uni.$u.toast('倒计时结束后再发送')
		}
	}
	
	// 密码登录
	const formRef1 = ref(null)
	const formData1 = ref({
		phone: '',
		password: ''
	})
	// 表单验证
	const rules1 = ref({
		phone: {
			rules: [{
				required: true,
				errorMessage: '请输入手机号码'
			}, {
				validateFunction: function (rule,value,data,callback) {
					if (!test.mobile(value)) {
						callback('请输入正确手机号码')
					}
					return true
				}
			}]
		},
		password: {
			rules: [{
				required: true,
				errorMessage: '请输入密码'
			}]
		}
	})
	
	const isSubmit = ref(false)
	const submitForm = (e) => {
		if (formData.value.phone == '88888888') {
			showUrl.value = true
			return false
		}
		if (!isAgreement.value) return uni.$u.toast('阅读并同意《服务协议》和《隐私政策》')
		
		if (tabsCurrent.value === 1) {
			formRef.value.validate().then(formRes => {
				isSubmit.value = true
				const params = {
					...formRes
				}
				// #ifdef MP-WEIXIN 
				appletBindPhone(params).then(res => {
					if (res.token) {
						uni.$u.toast('登录成功')
						setToken(res.token)
						userStore.getUserInfo()
						userStore.updateLogin()
						uni.$u.sleep(1000).then(() => {
							isSubmit.value = false
							uni.switchTab({
								url: '/pages/index/index'
							})
						})
					} else if (res?.code) {
						setStore.setBindPhone({
							...res.data,
							phone:params.phone
						})
						uni.$u.sleep(1000).then(() => {
							uni.navigateTo({
								url: `/pages/mine/correlation`
							})
							isSubmit.value = false
						})
					}
				}).catch(err => {
					isSubmit.value = false
				})
				// #endif
				// #ifndef MP-WEIXIN
				phoneCodeLogin(params).then(res => {
					if (res.token) {
						uni.$u.toast('登录成功')
						setToken(res.token)
						userStore.getUserInfo()
						userStore.updateLogin()
						uni.$u.sleep(1000).then(() => {
							isSubmit.value = false
							uni.switchTab({
								url: '/pages/index/index'
							})
						})
					} else if (res?.code) {
						setStore.setBindPhone({
							...res.data,
							phone:params.phone
						})
						uni.$u.sleep(1000).then(() => {
							uni.navigateTo({
								url: `/pages/mine/correlation`
							})
							isSubmit.value = false
						})
					}
				}).catch(err => {
					isSubmit.value = false
				})
				// #endif
			})
		}
		// #ifndef MP-WEIXIN
		else {
			formRef1.value.validate().then(formRes => {
				isSubmit.value = true
				const params = {
					...formRes
				}
				login(params).then(res => {
					if (res.token) {
						uni.$u.toast('登录成功')
						setToken(res.token)
						userStore.getUserInfo()
						userStore.updateLogin()
						uni.$u.sleep(1000).then(() => {
							isSubmit.value = false
							uni.switchTab({
								url: '/pages/index/index'
							})
						})
					}
				}).catch(err => {
					isSubmit.value = false
				})
			})
		}
		// #endif
		
	}
	const isAgreement = ref(false)
	const changeAgreement = () => {
		isAgreement.value = !isAgreement.value
	}
	// 查看协议
	const goAgreement = (type) => {
		uni.navigateTo({
			url: `/pages/web/web?type=${type}`
		})
	}
	// 暂不登录
	const submitBack = () => {
		uni.switchTab({
			url: '/pages/index/index'
		})
	}
	// 取消绑定
	const cancel = () => {
		uni.navigateBack({
			delta: 1
		})
	}
	
	// 密码登录
	const goLogin = () => {
		tabsCurrent.value = 0
	}
	// 注册
	const register = () => {
		uni.navigateTo({
			url: '/pages/login/register'
		})
	}
	// 忘记密码
	const forget = () => {
		uni.navigateTo({
			url: '/pages/mine/forget?type=1'
		})
	}
	
	
	// 切换域名
	const showUrl = ref(false)
	const closeUrl = () => {
		showUrl.value = false
	}
	const openUrl = () => {
		getUrlList()
	}
	const getUrlList = () => {
		// 获取服务器域名
		const list = uni.getStorageSync('tyUrlList')
		if (list && list.length > 0) {
			urlList.value = globalConfig.value.baseUrlList.concat(list)
		} else {
			urlList.value = globalConfig.value.baseUrlList
		}
	}
	const urlList = ref([])
	const chooseUrl = ref('')
	const groupChangeUrl = (e) => {
		// console.log(e)
	}
	const submitUrl = () => {
		if (!chooseUrl.value) {
		  uni.$u.toast("请输入服务器地址")
		} else if (!test.url(chooseUrl.value)) {
			uni.$u.toast("服务器地址不符合规范")
		} else if (urlList.value.indexOf(chooseUrl.value) === -1) {
			const oldUrlList = urlList.value.filter(item => globalConfig.value.baseUrlList.indexOf(item) === -1)
			if (oldUrlList.length >= 4) {
				oldUrlList.shift()
			}
			oldUrlList.push(chooseUrl.value)
			uni.setStorageSync('tyUrlList', oldUrlList)
			getUrlList()
		}
		setStore.setBaseUrl(chooseUrl.value)
		showUrl.value = false
		chooseUrl.value = ''
		formData.value.phone = ''
	}
	
	onReady(() => {
		formRef.value.setRules(rules.value)
		formRef1.value.setRules(rules1.value)
	})
</script>

<style lang="scss" scoped>
	.login {
		height: 100vh;
		padding: 0px 40rpx;
		box-sizing: border-box;
		flex-direction: column;
		&-app {
			width: 100%;
			text-align: center;
			margin-top: 120rpx;
		}
		&-bar {
			width: 100%;
		}
		&-content {
			width: 100%;
			margin: 80rpx 0;
			&-title {
				font-size: 28rpx;
				text-align: $text-light;
				margin-top: 40rpx;
			}
			&-form {
				margin-top: 40rpx;
			}
			&-btns {
				margin-top: 40rpx;
			}
			&-tabs {
				justify-content: center;
			}
		}
		&-logo {
			&-img {
				width: 200rpx;
				height: 200rpx;
				border-radius: 50%;
			}
		}
		&-name {
			font-size: 48rpx;
			font-weight: bold;
			margin-top: 20rpx;
		}
		&-btn {
			width: 100%;
			height: 80rpx;
			border-radius: 40rpx;
			font-size: 28rpx;
			justify-content: center;
			&+.login-btn {
				margin-top: 40rpx;
			}
		}
		&-code {
			&-btn {
				width: 110px;
				height: 36px;
				border-radius: 4px;
				padding: 0;
				margin: 0;
				margin-left: 20rpx;
				font-size: 14px;
				color: #ffffff;
				background-color: $primary-color;
				justify-content: center;
			}
		}
		&-tip {
			font-size: 24rpx;
			margin-top: 40rpx;
			text-align: center;
			&-register {
				color: #0273ff;
			}
		}
		&-forget {
			font-size: 24rpx;
			margin: 20rpx 0;
			text-align: right;
			color: #0273ff;
		}
		&-agreement {
			width: 100%;
			font-size: 28rpx;
			margin-top: 40rpx;
			justify-content: center;
			&-icon {
				margin-right: 10rpx;
			}
			&-item {
				color: #8c97cb;
			}
		}
	}
	.url {
		width: 600rpx;
		padding: 20rpx;
		&-title {
			font-size: 32rpx;
			font-weight: 600;
			text-align: center;
		}
		&-input {
			padding-top: 20rpx;
		}
		&-radio {
			padding: 20rpx 0;
		}
	}
</style>
